<template>
  <view v-if="isShow" class="message">
    <image v-if="isSuccess" class="icon success" src="@/assets/svgs/done.svg"></image>
    <image v-if="isError" class="icon error" src="@/assets/svgs/close.svg"></image>

    <view class="text" :class="{
      success: isSuccess,
      error: isError,
    }">
      <slot v-if="!message"></slot> {{ message ? message : "" }}
    </view>
  </view>
</template>

<script>
import { computed, nextTick, ref } from "vue";

export default {
  data() {
    return {
      timer: null,
      isShow: false,
      message: "",
      duration: 2000,
      type: "success"
    };
  },
  computed: {
    isSuccess() {
      return this.type === "success";
    },
    isError() {
      return this.type === "error";
    }
  },
  methods: {
    show(options) {
      if (this.isShow) {
        this.timer && clearTimeout(this.timer);
        this.isShow = false;
      }
      if (options.message) {
        if (options.duration) {
          this.duration = options.duration;
        } else {
          this.duration = 2000;
        }
        if (options.type) {
          this.type = options.type;
        } else {
          this.type = "success";
        }
        this.$nextTick(() => {
          this.isShow = true;
          this.message = options.message;
          this.timer = setTimeout(() => {
            this.isShow = false;
            options.complete && options.complete();
          }, this.duration);
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
@my-color-primary: #aa69ff;

.message {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 0.5rem 1rem;
  border-radius: 0.3rem;
  position: fixed;
  left: 50%;
  top: 5%;
  transform: translateX(-50%);
  min-width: 1rem;
  box-sizing: border-box;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
  animation: show 0.5s 1 ease-in-out;
  z-index: 99999;

  @keyframes show {
    from {
      opacity: 0;
      top: -10%;
    }
  }

  .icon {
    width: 1rem;
    height: 1rem;
    border-radius: 50%;
    margin-right: 0.5rem;

    &.success {
      background: @my-color-primary;
    }

    &.error {
      background: #ff4747d3;
    }
  }

  .text {
    display: inline;

    &.success {
      color: @my-color-primary;
    }

    &.error {
      color: #ff4747d3;
    }
  }
}
</style>